﻿using Encloser.Toolkit;
using System;

namespace Encloser.Configuration
{
    public class Config<T> : Atomic<T> where T : new()
    {
        private readonly string path;

        public Config(string path)
        {
            this.path = path;
            FileIO.Read<T>(path)
                .Try(conf => Value = conf)
                .Catch(() => Value = new T());
        }

        public void Dump()
        {
            Get(conf => FileIO.Write(path, conf));
        }

        public void Show(Action<T> postConfig = null)
        {
            var f = new ConfigForm<T>(Value);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (postConfig == null) postConfig(f.Result);
                Value = f.Result;
                FileIO.Write(path, f.Result);
            }
        }

        public void Show(Func<T, bool> postConfig = null)
        {
            var f = new ConfigForm<T>(Value);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (postConfig == null || !postConfig(f.Result)) return;
                Value = f.Result;
                FileIO.Write(path, f.Result);
            }
        }
    }
}
